﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
using System.Windows.Markup;
using System.Windows.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Diagnostics.Contracts;

namespace ShredTheLog.Controls
{
    public class SkinnableWindow : Window
    {
        #region Код, отвечающий за корректную максимизацию окна (http://blogs.msdn.com/llobo/archive/2006/08/01/Maximizing-window-_2800_with-WindowStyle_3D00_None_2900_-considering-Taskbar.aspx)

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);

            IntPtr hwnd = (new WindowInteropHelper(this)).Handle;
            HwndSource.FromHwnd(hwnd).AddHook(new HwndSourceHook(WindowProc));
        }

        private static IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            switch (msg)
            {
                case 0x0024:
                    WmGetMinMaxInfo(hwnd, lParam);

                    // Если раскомментировать эту строчку, то перестанут работать Window.MinWidth и Window.MinHeight у окон без скина (например, в теме Simple)
                    //handled = true;
                    
                    break;
            }

            return IntPtr.Zero;
        }

        private static void WmGetMinMaxInfo(IntPtr hwnd, IntPtr lParam)
        {
            MINMAXINFO mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));

            // Adjust the maximized size and position to fit the work area of the correct monitor
            int MONITOR_DEFAULTTONEAREST = 0x00000002;
            IntPtr monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);

            if (monitor != IntPtr.Zero)
            {
                MONITORINFO monitorInfo = new MONITORINFO();
                GetMonitorInfo(monitor, monitorInfo);
                RECT rcWorkArea = monitorInfo.rcWork;
                RECT rcMonitorArea = monitorInfo.rcMonitor;

                Contract.Assume(rcWorkArea.left - rcMonitorArea.left != Int32.MinValue);
                mmi.ptMaxPosition.x = Math.Abs(rcWorkArea.left - rcMonitorArea.left);
                
                Contract.Assume(rcWorkArea.top - rcMonitorArea.top != Int32.MinValue);
                mmi.ptMaxPosition.y = Math.Abs(rcWorkArea.top - rcMonitorArea.top);

                Contract.Assume(rcWorkArea.right - rcWorkArea.left != Int32.MinValue);
                mmi.ptMaxSize.x = Math.Abs(rcWorkArea.right - rcWorkArea.left);

                Contract.Assume(rcWorkArea.bottom - rcWorkArea.top != Int32.MinValue);
                mmi.ptMaxSize.y = Math.Abs(rcWorkArea.bottom - rcWorkArea.top);
            }

            Marshal.StructureToPtr(mmi, lParam, true);
        }

        /// <summary>
        /// POINT aka POINTAPI
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            /// <summary>
            /// x coordinate of point.
            /// </summary>
            public int x;
            /// <summary>
            /// y coordinate of point.
            /// </summary>
            public int y;

            /// <summary>
            /// Construct a point of coordinates (x,y).
            /// </summary>
            public POINT(int x, int y)
            {
                this.x = x;
                this.y = y;
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MINMAXINFO
        {
            public POINT ptReserved;
            public POINT ptMaxSize;
            public POINT ptMaxPosition;
            public POINT ptMinTrackSize;
            public POINT ptMaxTrackSize;
        };

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public class MONITORINFO
        {
            public int cbSize = Marshal.SizeOf(typeof(MONITORINFO));

            public RECT rcMonitor = new RECT();

            public RECT rcWork = new RECT();

            public int dwFlags = 0;
        }

        [StructLayout(LayoutKind.Sequential, Pack = 0)]
        public struct RECT
        {
            public int left;
            public int top;
            public int right;
            public int bottom;

            public static readonly RECT Empty = new RECT();

            public int Width
            {
                get 
                {
                    Contract.Requires(right - left != Int32.MinValue);

                    return Math.Abs(right - left); // Abs needed for BIDI OS
                }  
            }
            public int Height
            {
                get { return bottom - top; }
            }

            public RECT(int left, int top, int right, int bottom)
            {
                this.left = left;
                this.top = top;
                this.right = right;
                this.bottom = bottom;
            }

            public RECT(RECT rcSrc)
            {
                this.left = rcSrc.left;
                this.top = rcSrc.top;
                this.right = rcSrc.right;
                this.bottom = rcSrc.bottom;
            }

            public bool IsEmpty
            {
                get
                {
                    // BUGBUG : On Bidi OS (hebrew arabic) left > right
                    return left >= right || top >= bottom;
                }
            }
            /// <summary> Return a user friendly representation of this struct </summary>
            public override string ToString()
            {
                if (this == RECT.Empty) { return "RECT {Empty}"; }
                return "RECT { left : " + left + " / top : " + top + " / right : " + right + " / bottom : " + bottom + " }";
            }

            /// <summary> Determine if 2 RECT are equal (deep compare) </summary>
            public override bool Equals(object obj)
            {
                if (!(obj is Rect)) { return false; }
                return (this == (RECT)obj);
            }

            /// <summary>Return the HashCode for this struct (not garanteed to be unique)</summary>
            public override int GetHashCode()
            {
                return left.GetHashCode() + top.GetHashCode() + right.GetHashCode() + bottom.GetHashCode();
            }

            /// <summary> Determine if 2 RECT are equal (deep compare)</summary>
            public static bool operator ==(RECT rect1, RECT rect2)
            {
                return (rect1.left == rect2.left && rect1.top == rect2.top && rect1.right == rect2.right && rect1.bottom == rect2.bottom);
            }

            /// <summary> Determine if 2 RECT are different(deep compare)</summary>
            public static bool operator !=(RECT rect1, RECT rect2)
            {
                return !(rect1 == rect2);
            }
        }

        [DllImport("user32")]
        internal static extern bool GetMonitorInfo(IntPtr hMonitor, MONITORINFO lpmi);

        [DllImport("User32")]
        internal static extern IntPtr MonitorFromWindow(IntPtr handle, int flags);

        #endregion
    }

    public sealed class WindowIcon : Control
    {
        static WindowIcon()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WindowIcon), new FrameworkPropertyMetadata(typeof(WindowIcon)));
        }

        public static ImageSource GetIcon(DependencyObject obj)
        {
            return (ImageSource)obj.GetValue(IconProperty);
        }
        public static void SetIcon(DependencyObject obj, ImageSource value)
        {
            obj.SetValue(IconProperty, value);
        }
        public static readonly DependencyProperty IconProperty = DependencyProperty.RegisterAttached("Icon", typeof(ImageSource), typeof(WindowIcon), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits));
    }

    public abstract class WindowPartThumb : Thumb
    {
        static WindowPartThumb()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WindowPartThumb), new FrameworkPropertyMetadata(typeof(WindowPartThumb)));
        }

        private SkinnableWindow _window;
        public SkinnableWindow Window
        {
            get
            {
                if (_window == null)
                    _window = (SkinnableWindow)SkinnableWindow.GetWindow(this);
                return _window;
            }
        }
    }

    [ContentProperty("Title")]
    public sealed class WindowTitleBar : WindowPartThumb
    {
        static WindowTitleBar()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WindowTitleBar), new FrameworkPropertyMetadata(typeof(WindowTitleBar)));
        }

        public WindowTitleBar()
        {
            DragDelta +=
                (sender, e) =>
                {
                    Window.Left += e.HorizontalChange;
                    Window.Top += e.VerticalChange;
                };
        }

        protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
        {
            base.OnMouseDoubleClick(e);

            if (Window.ResizeMode == ResizeMode.CanResize || Window.ResizeMode == ResizeMode.CanResizeWithGrip)
            {
                Action action = () =>
                    Window.WindowState = Window.WindowState != WindowState.Maximized ?
                    WindowState.Maximized :
                    WindowState.Normal;
                Dispatcher.BeginInvoke(action, DispatcherPriority.SystemIdle);
            }
        }

        public object Title
        {
            get { return (string)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, value); }
        }
        public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(object), typeof(WindowTitleBar));
    }

    public class WindowBorder : WindowPartThumb
    {
        static WindowBorder()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WindowBorder), new FrameworkPropertyMetadata(typeof(WindowBorder)));
        }
    }

    #region Боковины рамки окна
    public sealed class WindowTopBorder : WindowBorder
    {
        static WindowTopBorder()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WindowTopBorder), new FrameworkPropertyMetadata(typeof(WindowTopBorder)));
        }

        public WindowTopBorder()
        {
            DragDelta +=
                (sender, e) =>
                {
                    var d = Math.Min(e.VerticalChange, Window.Height - Window.MinHeight);
                    Window.Top += d;
                    Window.Height -= d;
                };
        }
    }

    public sealed class WindowBottomBorder : WindowBorder
    {
        static WindowBottomBorder()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WindowBottomBorder), new FrameworkPropertyMetadata(typeof(WindowBottomBorder)));
        }

        public WindowBottomBorder()
        {
            DragDelta +=
                (sender, e) =>
                {
                    var d = Math.Max(e.VerticalChange, Window.MinHeight - Window.Height);
                    Window.Height += d;
                };
        }
    }

    public sealed class WindowLeftBorder : WindowBorder
    {
        static WindowLeftBorder()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WindowLeftBorder), new FrameworkPropertyMetadata(typeof(WindowLeftBorder)));
        }

        public WindowLeftBorder()
        {
            DragDelta +=
                (sender, e) =>
                {
                    var d = Math.Min(e.HorizontalChange, Window.Width - Window.MinWidth);
                    Window.Left += d;
                    Window.Width -= d;
                };
        }
    }

    public sealed class WindowRightBorder : WindowBorder
    {
        static WindowRightBorder()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WindowRightBorder), new FrameworkPropertyMetadata(typeof(WindowRightBorder)));
        }

        public WindowRightBorder()
        {
            DragDelta +=
                (sender, e) =>
                {
                    var d = Math.Max(e.HorizontalChange, Window.MinWidth - Window.Width);
                    Window.Width += d;
                };
        }
    }
    #endregion

    #region Уголки рамки окна
    public sealed class WindowTopLeftCorner : WindowBorder
    {
        static WindowTopLeftCorner()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WindowTopLeftCorner), new FrameworkPropertyMetadata(typeof(WindowTopLeftCorner)));
        }

        public WindowTopLeftCorner()
        {
            DragDelta +=
                (sender, e) =>
                {
                    var dx = Math.Min(e.HorizontalChange, Window.Width - Window.MinWidth);
                    Window.Left += dx;
                    Window.Width -= dx;
                    var dy = Math.Min(e.VerticalChange, Window.Height - Window.MinHeight);
                    Window.Top += dy;
                    Window.Height -= dy;
                };
        }
    }

    public sealed class WindowTopRightCorner : WindowBorder
    {
        static WindowTopRightCorner()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WindowTopRightCorner), new FrameworkPropertyMetadata(typeof(WindowTopRightCorner)));
        }

        public WindowTopRightCorner()
        {
            DragDelta +=
                (sender, e) =>
                {
                    var dx = Math.Max(e.HorizontalChange, Window.MinWidth - Window.Width);
                    Window.Width += dx;
                    var dy = Math.Min(e.VerticalChange, Window.Height - Window.MinHeight);
                    Window.Top += dy;
                    Window.Height -= dy;
                };
        }
    }

    public sealed class WindowBottomLeftCorner : WindowBorder
    {
        static WindowBottomLeftCorner()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WindowBottomLeftCorner), new FrameworkPropertyMetadata(typeof(WindowBottomLeftCorner)));
        }

        public WindowBottomLeftCorner()
        {
            DragDelta +=
                (sender, e) =>
                {
                    var dx = Math.Min(e.HorizontalChange, Window.Width - Window.MinWidth);
                    Window.Left += dx;
                    Window.Width -= dx;
                    var dy = Math.Max(e.VerticalChange, Window.MinHeight - Window.Height);
                    Window.Height += dy;
                };
        }
    }

    public sealed class WindowBottomRightCorner : WindowBorder
    {
        static WindowBottomRightCorner()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WindowBottomRightCorner), new FrameworkPropertyMetadata(typeof(WindowBottomRightCorner)));
        }

        public WindowBottomRightCorner()
        {
            DragDelta +=
                (sender, e) =>
                {
                    var dx = Math.Max(e.HorizontalChange, Window.MinWidth - Window.Width);
                    Window.Width += dx;
                    var dy = Math.Max(e.VerticalChange, Window.MinHeight - Window.Height);
                    Window.Height += dy;
                };
        }
    }
    #endregion

    #region Кнопки в заголовке окна
    public abstract class WindowTitleBarButton : Button
    {
        static WindowTitleBarButton()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WindowTitleBarButton), new FrameworkPropertyMetadata(typeof(WindowTitleBarButton)));
        }

        private Window _window;
        public Window Window
        {
            get
            {
                if (_window == null)
                    _window = Window.GetWindow(this);
                return _window;
            }
        }
    }

    public sealed class WindowMinimizeButton : WindowTitleBarButton
    {
        static WindowMinimizeButton()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WindowMinimizeButton), new FrameworkPropertyMetadata(typeof(WindowMinimizeButton)));
        }

        public WindowMinimizeButton()
        {
            Click += (sender, e) => Window.WindowState = WindowState.Minimized;
        }
    }

    public sealed class WindowMaximizeButton : WindowTitleBarButton
    {
        static WindowMaximizeButton()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WindowMaximizeButton), new FrameworkPropertyMetadata(typeof(WindowMaximizeButton)));
        }

        public WindowMaximizeButton()
        {
            Click += (sender, e) => Window.WindowState = Window.WindowState != WindowState.Maximized ? WindowState.Maximized : WindowState.Normal;
        }
    }

    public sealed class WindowCloseButton : WindowTitleBarButton
    {
        static WindowCloseButton()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WindowCloseButton), new FrameworkPropertyMetadata(typeof(WindowCloseButton)));
        }

        public WindowCloseButton()
        {
            Click += (sender, e) => Window.Close();
        }
    }
    #endregion
}
